package com.dengxiujun.simpletomcat.container;

import com.dengxiujun.simpletomcat.handler.ConnectionHandler;
import com.dengxiujun.simpletomcat.config.ServletMappingConfig;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

/**
 * <p></p>
 *
 * @author dengxiujun
 * @date 2021-04-26
 **/
public class ServletContainer {

    private int port;

    public ServletContainer(int port) {
        this.port = port;
    }

    public void start() {
        ServletMappingConfig.initServletMapping();
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("Tomcat 容器启动成功!");
            while (true) {
                Socket socket = serverSocket.accept();
                executorService.execute(new ConnectionHandler(socket));
            }
        } catch (IOException e) {
            System.out.println("simple-tomcat 启动失败!");
            e.printStackTrace();
        } finally {
            executorService.shutdown();
        }
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

}
